package com.alm.token.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alm.token.ConStant;
import com.alm.token.MyApp;
import com.alm.token.R;
import com.alm.token.base.BaseActivity;
import com.alm.token.base.BaseAdapter;
import com.alm.token.common.RefreshLoadMoreManager;
import com.alm.token.ui.data.bean.G12CanData;
import com.alm.token.ui.data.bean.UserListLHData;
import com.alm.token.ui.persenter.MyPreenter;
import com.alm.token.ui.view.QuantitativeOrderOpenAddView;
import com.alm.token.utils.ActionBarHelper;
import com.alm.token.utils.CommonUtil;
import com.chad.library.adapter.base.BaseViewHolder;
import com.haozhang.lib.SlantedTextView;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import baibeiwallet.Constant;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class QuantitativeOrderActivity extends BaseActivity implements QuantitativeOrderOpenAddView<Object> {
    @BindView(R.id.leftItem)
    ImageView leftItem;
    @BindView(R.id.centerItem)
    TextView centerItem;
    @BindView(R.id.rightItem)
    TextView rightItem;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.open_btn)
    RelativeLayout openBtn;
    @BindView(R.id.open_supervip)
    RelativeLayout supervipBtn;
    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.tv_clickreload)
    TextView tvClickreload;
    @BindView(R.id.nodatashow_body)
    RelativeLayout nodatashowBody;


    private RefreshLoadMoreManager<UserListLHData.DataBean> manager;
    private List<UserListLHData.DataBean> dataBeans = new ArrayList<>();
    private List<UserListLHData.DataBean> dataBeansGuanbi = new ArrayList<>();
    private List<UserListLHData.DataBean> dataBeansJinxing = new ArrayList<>();
    private int ActivityForResultCode = 1;

    private int limit = 100, page = 1;
    private boolean isfull = false;

    @Override
    protected MyPreenter initPreenter() {
        return new MyPreenter(this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_quantitative_order;
    }

    @Override
    protected void initVariables() {

    }

    @Override
    protected void initViews() {
        new ActionBarHelper(this)
                .setTitle(getString(R.string.title_hint_item29))
                .setRightIcon(R.drawable.lh_order, this);


        openBtn.setOnClickListener(this);
        rightItem.setOnClickListener(this);
        supervipBtn.setOnClickListener(this);
        initManager();
        swipeRefreshLayout.setVisibility(View.GONE);
        nodatashowBody.setVisibility(View.VISIBLE);
    }

    private void initManager() {
        OrderAdapter adapter = new OrderAdapter(this);
        manager = new RefreshLoadMoreManager.Builder(this)
                .setAdapter(adapter)
                .setRecyclerView(recyclerView)
                .setOnListItemClickListener(new RefreshLoadMoreManager.OnListItemClickListener() {
                    @Override
                    public void onListItemClick(BaseAdapter.BaseItem item, int position) {
                        if (dataBeansJinxing != null && dataBeansJinxing.size() > position) {
                            Intent intent = new Intent(QuantitativeOrderActivity.this, QuantitativeOrderDetailActivity.class);
                            intent.putExtra("databean", dataBeansJinxing.get(position));
                            startActivityForResult(intent, ActivityForResultCode);
                        }
//                        startActivity(QuantitativeOrderDetailActivity.class);
                    }
                })
                .setSwipeRefreshLayout(swipeRefreshLayout)
                .setOnRefreshListener(new RefreshLoadMoreManager.OnRefreshListener() {
                    @Override
                    public void onRefresh() {
//                        showToast("onRefresh");
                        swipeRefreshLayout.setRefreshing(false);
                        loadData();
                    }
                })
                .build();
//                .setOpenLoadMore(true)
//                .setOnLoadMoreListener(new RefreshLoadMoreManager.OnLoadMoreListener() {
//                    @Override
//                    public void onLoadMore() {
//                        manager.getAdapter().loadMoreEnd(true);
//                        manager.getAdapter().loadMoreFail();
//                        showWaitDialog();
//                        preenter.getUserListLHData(String.valueOf(limit), String.valueOf(page));
//                    }
//                })
        recyclerView.setNestedScrollingEnabled(false);
    }

    @Override
    protected void loadData() {
        limit = 100;
        page = 1;
        preenter.getUserListLHData(String.valueOf(limit), String.valueOf(page));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.open_btn:
//                startActivityForResult(QuantitativeOrderOpenAddActivity.class, ActivityForResultCode);
                startActivityForResult(QuantitativeSplashActivity.class, ActivityForResultCode);
                break;
            case R.id.rightItem:
                startActivity(LH2OrderHistoryActivity.class);
                break;

            case R.id.open_supervip:
                //解除 查询 当期vip订单
//                Intent intent = new Intent(QuantitativeOrderActivity.this, VipApplySplashActivity.class);
                Intent intent = new Intent(QuantitativeOrderActivity.this, VipApplyActivity.class);
                intent.putExtra("intentType", 1);
                startActivity(intent);
                break;

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ActivityForResultCode) {
            if (resultCode == QuantitativeOrderOpenAddActivity.AddAppendSucc) {
//                showToast("添加成功，刷新列表");
                loadData();
            }
            if (resultCode == QuantitativeOrderDetailActivity.AppendSucc) {
//                showToast("添加成功，刷新列表");
                loadData();
            }
        }
    }

    @Override
    public void getData(Object o) {

    }

    @Override
    public void jumpToLoginAct(int staue) {
        if (staue == 3) {
//            showToast(getString(R.string.common_relogin));
//            Intent intent = new Intent();
//            intent.setAction(ConStant.EXIT_APP);
//            sendBroadcast(intent);
//            startActivity(BlockWalletLoginActivity.class);
//            finish();
        } else if (staue == 4) {
//            showToast(getString(R.string.paypasw_hint_setpaypsw));
//            Intent intent = new Intent(this,PayPwdActivity.class);
//            intent.putExtra("PayPwdActivityType",PayPwdActivity.PAYPSW_SET);
//            startActivity(intent);
//            finish();
            showToSetPaypswDialog();
        }else if (staue == 666) {
            showToUpdata();
        }
    }

    @Override
    public void onError(String error) {
        showToast(getString(R.string.common_loaderrritry));
    }

    @Override
    public void ShowProgress() {

        showWaitDialog();
    }

    @Override
    public void hideProgress() {
        hideWaitDialog();
    }

    @Override
    public void getShowUserXingjiData(Object o) {

    }

    @Override
    public void getAddLhOrderData(Object o) {

    }

    @Override
    public void getAppendOrderData(Object o) {

    }

    @Override
    public void getCloseOrderData(Object o) {

    }

    @Override
    public void getZhuijiashowData(Object o) {

    }

    @Override
    public void getUserListLHData(Object userListLHData) {

        if (userListLHData instanceof UserListLHData) {
            UserListLHData data = (UserListLHData) userListLHData;
            if (data.getStatus() == 0 && data.getData() != null) {
                dataBeans.clear();
                dataBeansGuanbi.clear();
                dataBeansJinxing.clear();
                dataBeans.addAll(data.getData());

                for (int i = 0; i < dataBeans.size(); i++) {
                    dataBeans.get(i).setLayoutId(OrderAdapter.LAYOUT_ID);
                    if (Integer.parseInt(dataBeans.get(i).getOrderStatus()) != 0) {
                        dataBeansGuanbi.add(dataBeans.get(i));
                    } else {
                        dataBeansJinxing.add(dataBeans.get(i));
                    }
                }
                MyApp.setDataBeansGuanbi(dataBeansGuanbi);
                manager.setData(dataBeansJinxing);

            } else showToast(data.getMsg());
        }

        if (dataBeansJinxing.size() == 0) {
            swipeRefreshLayout.setVisibility(View.GONE);
            nodatashowBody.setVisibility(View.VISIBLE);
        } else {
            swipeRefreshLayout.setVisibility(View.VISIBLE);
            nodatashowBody.setVisibility(View.GONE);
        }
    }

    @Override
    public void getG12CanData(G12CanData g12CanData) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick(R.id.tv_clickreload)
    public void onViewClicked() {
        loadData();
    }

    public class OrderAdapter extends BaseAdapter<UserListLHData.DataBean> {

        public static final int LAYOUT_ID = R.layout.item_quantitative_order;

        public OrderAdapter(@NonNull Context context) {
            super(context);
        }

        @Override
        protected void convert(BaseViewHolder helper, UserListLHData.DataBean item, int itemType) {

            helper.setText(R.id.tv_orderid, item.getOrderid());
            DecimalFormat dec = new DecimalFormat("0.0000");
            StringBuffer shuliang1 = new StringBuffer();
            if (item.getBizhong() != null && item.getBizhong().size() != 0) {
                for (int i = 0; i < item.getBizhong().size(); i++) {
                    shuliang1.append(dec.format(item.getBizhongMoney().get(i)) + " " + item.getBizhong().get(i) +(i==item.getBizhong().size()-1?"":i%2==1?"\n":"/") );
                }
            } else {
                shuliang1.append(dec.format(0) + " ETH");
            }
            String shuliang2 = item.getBizhong1() + " " + dec.format(item.getBizhongMoney1());
            helper.setText(R.id.tv_shuliang, shuliang1.toString());
            helper.setText(R.id.tv_shuliang2, shuliang2);
//            helper.setText(R.id.tv_yaoqingma, "  开启数量" + item.getYaoqingma());
            helper.setText(R.id.tv_lejiday, item.getLejiday().replace("-","") + "Days");
            helper.setText(R.id.tv_start, "Start: " + CommonUtil.getDateTimeFromMillisecond(Long.parseLong(item.getStart())).split(" ")[0]);
//            if (item.getEnd() != null && Long.parseLong(item.getEnd()) != 0) {
//                helper.setVisible(R.id.tv_end, true);
//                helper.setText(R.id.tv_end, "结束时间:" + CommonUtil.getDateTimeFromMillisecond(Long.parseLong(item.getEnd())).split(" ")[0]);
//            } else {
//                helper.setVisible(R.id.tv_end, false);
//            }
            helper.setText(R.id.tv_yuji, "Expire: " + CommonUtil.getDateTimeFromMillisecond(Long.parseLong(item.getYuji())).split(" ")[0]);
//            helper.setText(R.id.tv_leji, "累计收益:" + item.getLeji());
            SlantedTextView imgOrdertype = helper.getView(R.id.img_ordertype);
            if (Integer.parseInt(item.getOrderStatus()) != 0) {
                imgOrdertype.setText(getString(R.string.alphago_hint_ygb))
                        .setTextColor(getResources().getColor(R.color.quanlitative_flag3))
                        .setSlantedBackgroundColor(getResources().getColor(R.color.quanlitative_flag2))
                        .setTextSize(11)
                        .setSlantedLength(55)
                        .setMode(SlantedTextView.MODE_RIGHT_TRIANGLE);
            } else {
                imgOrdertype.setText(getString(R.string.alphago_hint_jxz))
                        .setTextColor(Color.WHITE)
                        .setSlantedBackgroundColor(getResources().getColor(R.color.quanlitative_flag1))
                        .setTextSize(11)
                        .setSlantedLength(55)
                        .setMode(SlantedTextView.MODE_RIGHT_TRIANGLE);
            }
            LinearLayout xinjiBody = helper.getView(R.id.ly_xinjibody);
            int ll1 = Integer.parseInt(item.getXingji());
            if (ll1 <= xinjiBody.getChildCount()) {
                for (int i = 0; i < xinjiBody.getChildCount(); i++) {//4number  i=0-3
                    if (i < ll1) { //i=0 1 2 3  ll1=1 2 3 4
                        xinjiBody.getChildAt(i).setVisibility(View.VISIBLE);
                    } else {
                        xinjiBody.getChildAt(i).setVisibility(View.GONE);
                    }
                }
            }
        }

    }
}
